<template>
    <div class="home-wrapper">
        <div class="app-container">
            <!-- 侧边导航栏 -->
            <div class="side-select">
                <div class="sidebar-header">
                    <h2><i class="fas fa-brain"></i> 模型训练中心</h2>
                </div>

                <div class="nav-items">
                    <div class="nav-item"
                         :class="{ active: activeTab === 'chat' }"
                         @click="activeTab = 'chat'">
                        <div class="fas fa-comments"></div>
                        <span>聊天页面</span>
                    </div>
                    <div class="nav-item"
                         :class="{ active: activeTab === 'history' }"
                         @click="jumpToHistory">
                        <div class="fas fa-history"></div>
                        <span>历史会话</span>
                    </div>
                    <div class="nav-item"
                         :class="{ active: activeTab === 'incremental' }"
                         @click="activeTab = 'incremental'">
                        <div class="fas fa-plus-circle"></div>
                        <span>增量学习页面</span>
                    </div>
                    <div class="nav-item"
                         :class="{ active: activeTab === 'recognition' }"
                         @click="jumpToRecognition">
                        <div class="fas fa-search"></div>
                        <span>识别结果</span>
                    </div>
                    <div class="nav-item"
                         :class="{ active: activeTab === 'reports' }"
                         @click="activeTab = 'reports'">
                        <div class="fas fa-chart-bar"></div>
                        <span>数据报告</span>
                    </div>

                </div>

                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />

                <div class="sidebar-footer">
                    <button class="logout-btn" @click="handleLogout">
                        <span>登 出</span>
                    </button>
                    <div class="model-info">
                        <div class="fas fa-microchip"></div>
                        <span>模型: QWen</span>
                    </div>
                    <div class="connection-status">
                        <div :class="['status-indicator', connectionStatusClass]">
                            <div class="status-dot"></div>
                            <span>{{ connectionStatusText }}</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 主内容区域各页面加main-page-card类，内容区只做内容布局 -->
            <div class="main-content">
                <div v-if="activeTab === 'chat'" class="main-page-card">
                    <div class="container">
                        <!-- 聊天页面 -->
                        <div class="header">
                            <h1>AI助手聊天界面</h1>
                            <p>连接大语言模型，实现智能对话</p>
                        </div>

                        <div class="chat-container">
                            <!-- 左侧图片上传与预览区域，只保留图片按钮和图片信息 -->
                            <div class="image-upload-side">
                                <!-- 上传图片按钮（大号） -->
                                <div class="file-upload file-upload-side">
                                    <button title="上传图片" @click="openFileSelector">
                                        <i class="fas fa-image"></i>
                                    </button>
                                    <input ref="fileInput"
                                           type="file"
                                           accept="image/*，video/*"
                                           multiple
                                           @change="handleImageUpload"
                                           style="display: none">
                                </div>
                                <!-- 新增：图片标签输入框 -->
                                <input class="image-tag-input" v-model="imageTag" placeholder="请输入图片标签" />
                                <!-- 图片名称卡片列表（无缩略图，红色圆角背景） -->
                                <div v-if="uploadedFiles.length > 0" class="image-name-list-side">
                                    <div v-for="(file, idx) in uploadedFiles" :key="idx" class="image-name-card-side">
                                        <span class="image-name-text">{{ file.name }}</span>
                                        <button class="remove-image-btn-name" @click="removeFile(idx)"><i class="fas fa-times"></i></button>
                                    </div>
                                </div>
                            </div>
                            <!-- 聊天消息区 -->
                            <div class="chat-history" ref="chatHistory">
                                <div v-for="(msg, index) in messages" :key="index" class="message" :class="`${msg.sender}-message`">
                                    <div class="message-header">
                                        <span>{{ msg.sender === 'user' ? '您' : '电力检测 AI' }}</span>
                                        <span>{{ msg.timestamp }}</span>
                                    </div>
                                    <div class="message-content">{{ msg.content }}</div>
                                    <!-- 支持多图 -->
                                    <div v-if="msg.images">
                                        <img v-for="(img, i) in msg.images" :key="i" :src="img" alt="上传的图片" style="margin-top:8px;max-width:220px;max-height:180px;border-radius:10px;">
                                    </div>
                                    <!-- 新增: 识别结果跳转按钮 -->
                                    <div v-if="msg.isJumpButton" class="jump-button-container">
                                        <button @click="jumpToRecognition">
                                            <i class="fas fa-search"></i> 查看识别结果
                                        </button>
                                    </div>
                                    <img v-else-if="msg.image" :src="msg.image" alt="上传的图片">
                                </div>
                                <div v-if="isTyping" class="message ai-message">
                                    <div class="typing-indicator">
                                        正在输入
                                        <div class="typing-dots">
                                            <div class="typing-dot"></div>
                                            <div class="typing-dot"></div>
                                            <div class="typing-dot"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 聊天输入区：左侧只保留滑动开关 -->
                        <div class="input-area">
                            <div class="switch-area-input">
                                <label class="switch">
                                    <input type="checkbox" v-model="showSwitch">
                                    <span class="slider"></span>
                                </label>
                                <div class="switch-label">
                                    {{ showSwitch ? '思考模式' : '快速模式' }}
                                </div>
                            </div>

                            <div class="text-input">
                                <textarea ref="textArea"
                                          v-model="messageInput"
                                          placeholder="输入消息..."
                                          @keyup.enter.exact="sendMessage"
                                          @keyup.ctrl.enter="addNewLine"
                                          @input="adjustTextareaHeight"></textarea>
                            </div>
                            <div class="send-btn"
                                 @click="sendMessage"
                                 :disabled="isSending"
                                 :class="{ 'sending': isSending }"
                                 :title="isSending ? '正在回答...' : '发送消息'">
                                <i v-if="!isSending" class="fas fa-paper-plane"></i>
                                <div v-else class="loading-spinner-small"></div>
                            </div>
                        </div>

                        <div class="status-bar">
                            <div class="status-item">
                                <i class="fas fa-plug status-icon"></i>
                                <span>已连接至服务器</span>
                            </div>
                            <div class="status-item">
                                <i class="fas fa-sync-alt status-icon"></i>
                                <span>模型: QWen </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="activeTab === 'history'" class="main-page-card">
                    <div class="history-page">
                        <!-- 历史会话页面内容 -->
                        <div class="page-header">
                            <h1><i class="fas fa-history"></i> 历史会话记录</h1>
                            <p>查看和管理您与AI的过往对话</p>
                        </div>

                        <div class="history-container">
                            <!-- 搜索和控制区域 - 现在放在中间上方 -->
                            <div class="search-controls-container">
                                <div class="search-controls">
                                    <div class="search-box">
                                        <i class="fas fa-search"></i>
                                        <input type="text"
                                               v-model="searchQuery"
                                               placeholder="搜索会话..."
                                               @keyup.enter="loadHistory">
                                    </div>
                                    <div class="filter-controls">
                                        <select v-model="dateFilter" @change="loadHistory">
                                            <option value="all">所有时间</option>
                                            <option value="today">今天</option>
                                            <option value="week">本周</option>
                                            <option value="month">本月</option>
                                            <option value="year">今年</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- 历史记录列表 -->
                            <div class="history-content">
                                <div class="history-list-container">
                                    <div v-if="filteredHistory.length === 0" class="empty-state">
                                        <i class="fas fa-inbox"></i>
                                        <p>没有找到历史会话记录</p>
                                    </div>

                                    <div v-for="session in filteredHistory" :key="session.id"
                                         class="history-item"
                                         :class="{ active: selectedSession?.id === session.id }"
                                         @click="selectSession(session)">
                                        <div class="session-preview">
                                            <div class="session-title">
                                                {{ session.title || '未命名会话' }}
                                            </div>
                                            <div class="session-snippet">
                                                {{ session.lastMessage || '无消息内容' }}
                                            </div>
                                        </div>
                                        <div class="session-meta">
                                            <div class="session-date">
                                                {{ formatDate(session.createdAt) }}
                                            </div>
                                            <!-- 添加 v-if 条件到整个操作按钮容器 -->
                                            <div class="session-actions" v-if="!selectedSession">
                                                <button class="action-btn restore-btn" @click.stop="restoreSession(session)">
                                                    <i class="fas fa-external-link-alt"></i>
                                                </button>
                                                <button class="action-btn delete-btn" @click.stop="confirmDelete(session)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div v-if="selectedSession" class="session-detail">
                                    <div class="detail-header">
                                        <h3>{{ selectedSession.title || '会话详情' }}</h3>
                                        <div class="header-actions">
                                            <span class="session-date">{{ formatDate(selectedSession.createdAt) }}</span>
                                            <button class="close-detail" @click="selectedSession = null">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="detail-content">
                                        <div v-for="(msg, index) in selectedSession.messages" :key="index"
                                             class="history-message" :class="`${msg.sender}-message`">
                                            <div class="message-header">
                                                <span>{{ msg.sender === 'user' ? '您' : '电力检测 AI' }}</span>
                                                <span>{{ msg.timestamp }}</span>
                                            </div>
                                            <div class="message-content">{{ msg.content }}</div>
                                            <!-- 支持多图和base64图片 -->
                                            <template v-if="msg.images && msg.images.length">
                                                <img v-for="(img, i) in msg.images" :key="'img'+i" :src="img" alt="历史图片" style="margin-top:8px;max-width:220px;max-height:180px;border-radius:10px;">
                                            </template>
                                            <template v-if="msg.base64_images && msg.base64_images.length">
                                                <img v-for="(img, i) in msg.base64_images" :key="'b64'+i" :src="img" alt="历史图片" style="margin-top:8px;max-width:220px;max-height:180px;border-radius:10px;">
                                            </template>
                                        </div>
                                    </div>
                                    <div class="detail-actions">
                                        <button class="action-btn primary" @click="restoreSession(selectedSession)">
                                            <i class="fas fa-external-link-alt"></i> 恢复会话
                                        </button>
                                        <button class="action-btn" @click="exportSession(selectedSession)">
                                            <i class="fas fa-download"></i> 导出会话
                                        </button>
                                        <button class="action-btn danger" @click="confirmDelete(selectedSession)">
                                            <i class="fas fa-trash"></i> 删除会话
                                        </button>
                                    </div>
                                </div>

                                <!-- 删除确认对话框 -->
                                <div v-if="showDeleteConfirm" class="modal-overlay" @click.self="showDeleteConfirm = false">
                                    <div class="confirm-modal">
                                        <div class="modal-header">
                                            <h3><i class="fas fa-exclamation-triangle"></i> 确认删除</h3>
                                            <button class="close-modal" @click="showDeleteConfirm = false">
                                                <i class="fas fa-times"></i>
                                            </button>
                                        </div>
                                        <div class="modal-body">
                                            <p>确定要删除会话 "{{ sessionToDelete?.title || '未命名会话' }}" 吗？此操作不可撤销。</p>
                                        </div>
                                        <div class="modal-footer">
                                            <button class="cancel-btn" @click="showDeleteConfirm = false">
                                                <i class="fas fa-times"></i> 取消
                                            </button>
                                            <button class="confirm-btn danger" @click="deleteSession" :disabled="isDeleting">
                                                <i class="fas fa-trash"></i>
                                                <span v-if="!isDeleting">确认删除</span>
                                                <span v-else>删除中...</span>
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <!-- 删除成功提示 -->
                                <div v-if="showDeleteSuccess" class="notification success">
                                    <i class="fas fa-check-circle"></i>
                                    <span>会话已成功删除</span>
                                    <button class="close-notification" @click="showDeleteSuccess = false">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>

                                <!-- 删除失败提示 -->
                                <div v-if="deleteError" class="notification error">
                                    <i class="fas fa-exclamation-circle"></i>
                                    <span>{{ deleteError }}</span>
                                    <button class="close-notification" @click="deleteError = null">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="activeTab === 'incremental'" class="main-page-card">
                    <div class="incremental-page">
                        <!-- 增量学习页面内容 -->
                        <div class="page-header">
                            <h1><i class="fas fa-plus-circle"></i> 增量学习</h1>
                            <p>通过添加新的标注数据来增强模型能力</p>
                        </div>

                        <div class="incremental-container">
                            <div class="info-card">
                                <div class="card-icon">
                                    <i class="fas fa-info-circle"></i>
                                </div>
                                <div class="card-content">
                                    <h3>增量学习说明</h3>
                                    <p>通过上传新的标注数据（图片+描述+类别），系统将安全高效地更新模型参数，使模型适应新的场景变化。</p>
                                    <ul>
                                        <li>支持图片上传（JPG, PNG格式）</li>
                                        <li>提供场景描述文本</li>
                                        <li>选择或输入新类别</li>
                                        <li>模型将进行自适应增量学习</li>
                                    </ul>
                                </div>
                            </div>

                            <div class="incremental-form">
                                <h2><i class="fas fa-upload"></i> 添加新训练数据</h2>

                                <div class="form-section">
                                    <h3>上传图片</h3>
                                    <div class="image-upload-box" @click="openIncrementalFileSelector">
                                        <div v-if="!incrementalImage" class="upload-prompt">
                                            <i class="fas fa-cloud-upload-alt"></i>
                                            <p>点击上传图片 (JPG, PNG)</p>
                                        </div>
                                        <img v-else :src="incrementalImagePreview" alt="上传的图片" class="uploaded-image">
                                        <input ref="incrementalFileInput"
                                               type="file"
                                               accept="image/*"
                                               @change="handleIncrementalImageUpload"
                                               style="display: none">
                                    </div>
                                    <button v-if="incrementalImage" class="remove-btn" @click="removeIncrementalImage">
                                        <i class="fas fa-trash"></i> 移除图片
                                    </button>
                                </div>

                                <!-- 新增: 1.1 是否有异物 -->
                                <div class="form-section">
                                    <h3>是否有异物</h3>
                                    <div class="radio-group">
                                        <label class="radio-label">
                                            <input type="radio" v-model="hasForeignObject" :value="true">
                                            <span class="radio-custom"></span>
                                            是
                                        </label>
                                        <label class="radio-label">
                                            <input type="radio" v-model="hasForeignObject" :value="false">
                                            <span class="radio-custom"></span>
                                            否
                                        </label>
                                    </div>
                                </div>

                                <!-- 新增: 1.2 选择异物类型 (根据是否有异物显示) -->
                                <div class="form-section" v-if="hasForeignObject === true || hasForeignObject === null">
                                    <h3>选择异物类型</h3>
                                    <div class="category-selector">
                                        <select v-model="foreignObjectType">
                                            <option value="" disabled>请选择异物类型</option>
                                            <option value="kite">风筝</option>
                                            <option value="trash">垃圾</option>
                                            <option value="bird_nest">鸟巢</option>
                                            <option value="balloon">气球</option>
                                            <option value="other">其他</option>
                                        </select>
                                        <div v-if="foreignObjectType === 'other'" class="new-category-input">
                                            <input type="text"
                                                   v-model="otherForeignObjectType"
                                                   placeholder="请输入其他异物类型">
                                        </div>
                                    </div>
                                </div>

                                <!-- 新增: 1.3 选择部件类型 (根据是否有异物显示) -->
                                <div class="form-section" v-if="hasForeignObject === false">
                                    <h3>选择图中的部件类型</h3>
                                    <div class="category-selector">
                                        <select v-model="componentType">
                                            <option value="" disabled>请选择部件类型</option>
                                            <option value="equalizing_ring">均压环</option>
                                            <option value="composite_insulator">复合绝缘子</option>
                                            <option value="hanging_point_hardware">挂点金具</option>
                                            <option value="glass_insulator">玻璃绝缘子</option>
                                            <option value="connecting_hardware">连接金具</option>
                                            <option value="vibration_damper">防震锤</option>
                                            <option value="other">其他</option>
                                        </select>
                                        <div v-if="componentType === 'other'" class="new-category-input">
                                            <input type="text"
                                                   v-model="otherComponentType"
                                                   placeholder="请输入其他部件类型">
                                        </div>
                                    </div>
                                </div>

                                <!-- 新增: 1.4 描述图中异物/部件位置 -->
                                <div class="form-section">
                                    <h3 v-text="locationLabel"></h3>
                                    <textarea v-model="locationDescription"
                                              :placeholder="locationPlaceholder"
                                              rows="3"></textarea>
                                </div>

                                <!--<h3>2. 场景描述</h3>
                                    <textarea v-model="sceneDescription"
                                              placeholder="请输入详细的场景描述..."
                                              rows="4"></textarea>
                                </div>-->

                                <div class="form-actions">
                                    <button class="submit-btn" :disabled="!isFormValid" @click="submitIncrementalData">
                                        <i class="fas fa-rocket"></i> 提交训练数据
                                    </button>
                                    <button class="reset-btn" @click="resetForm">
                                        <i class="fas fa-redo"></i> 重置表单
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="activeTab === 'recognition'" class="main-page-card">
                    <div class="recognition-page">
                        <!-- 识别结果页面内容 -->
                        <div class="page-header">
                            <h1><i class="fas fa-search"></i> 识别结果</h1>
                            <p>查看和管理AI模型的识别结果与检测报告</p>
                        </div>

                        <div class="recognition-container">
                            <!-- 左侧面板 (搜索, 筛选, 文件夹) -->
                            <div class="recognition-left-panel">
                                <!-- 搜索和筛选区域 -->
                                <div class="search-controls-container">
                                    <div class="search-controls">
                                        <div class="search-box">
                                            <i class="fas fa-search"></i>
                                            <input type="text"
                                                   v-model="groupSearchQuery"
                                                   placeholder="搜索文件夹...">
                                        </div>
                                        <div class="filter-controls">
                                            <div style="display: flex; gap: 15px; align-items: center; width: 100%;">
                                                <select v-model="recognitionDateFilter" @change="loadRecognitionResults">
                                                    <option value="all">所有时间</option>
                                                    <option value="today">今天</option>
                                                    <option value="week">本周</option>
                                                    <option value="month">本月</option>
                                                    <option value="year">今年</option>
                                                </select>
                                                <button class="mode-toggle-btn" @click="toggleMode">
                                                    <i class="fas fa-sync-alt"></i> <span>{{ modeText }}</span>
                                                </button>
                                            </div>
                                            <div style="display: flex; gap: 15px; align-items: center; width: 100%;">
                                                <select v-model="selectedForeignObjectStatus">
                                                    <option v-for="opt in foreignObjectStatusOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
                                                </select>
                                                <select v-if="selectedForeignObjectStatus === '存在异物'" v-model="selectedType">
                                                    <option value="" disabled selected>异物类型</option>
                                                    <option v-for="opt in foreignObjectTypeOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
                                                </select>
                                                <select v-if="selectedForeignObjectStatus === '无异物'" v-model="selectedType">
                                                    <option value="" disabled selected>部件类型</option>
                                                    <option v-for="opt in componentTypeOptions" :key="opt.value" :value="opt.value">{{ opt.label }}</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <button class="downloadExcel" @click="downloadAllGroupsExcel">
                                    <i class="fas fa-download"></i> <span>导出Excel</span>
                                </button>
                                <!-- 分组文件夹区域 -->
                                <div class="folder-category-box">
                                    <div class="folder-item"
                                         :class="{ active: selectedGroupId === null }"
                                         @click="onGroupChange(null)">
                                        <i class="fas fa-folder-open"></i>
                                        <span>所有识别结果</span>
                                    </div>
                                    <div v-for="group in filteredGroupList"
                                         :key="group.id"
                                         class="folder-item"
                                         :class="{ active: selectedGroupId === group.id }"
                                         @click="onGroupChange(group)">
                                        <i class="fas fa-folder"></i>
                                        <span>{{ group.title }}</span>
                                    </div>
                                </div>
                            </div>

                            <!-- 识别结果内容 -->
                            <div class="recognition-content">
                                <!-- 结果列表 -->
                                <div v-if="!isDetailedMode" class="recognition-list-container">
                                    <div v-if="filteredRecognitionResults.length === 0" class="empty-state">
                                        <i class="fas fa-search"></i>
                                        <p>没有找到识别结果</p>
                                    </div>

                                    <div v-for="result in filteredRecognitionResults" :key="result.id"
                                         class="recognition-item"
                                         :class="{ active: selectedResult?.id === result.id }"
                                         @click="viewResult(result)">
                                        <div class="result-preview">
                                            <div class="result-image">
                                                <img :src="result.imageUrl" :alt="result.title">
                                            </div>
                                            <div class="result-info">
                                                <div class="result-title">{{ getRecognitionTitle(result) }}</div>
                                                <div class="result-description">{{ getRecognitionDescription(result) }}</div>
                                                <div class="result-meta">
                                                    <span class="timestamp">{{ formatDate(result.timestamp) }}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="result-actions">
                                            <button class="action-btn view-btn" @click.stop="viewResult(result)">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="action-btn export-btn" @click.stop="exportResult(result)">
                                                <i class="fas fa-download"></i>
                                            </button>
                                            <button class="action-btn delete-btn" @click.stop="deleteResult(result)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <div v-else class="recognition-table-container">
                                    <div v-if="filteredRecognitionResults.length === 0" class="empty-state">
                                        <i class="fas fa-search"></i>
                                        <p>没有找到识别结果</p>
                                    </div>
                                    <table class="recognition-table">
                                        <thead>
                                            <tr>
                                                <th>图片</th>
                                                <th>是否有异物</th>
                                                <th>异物或部件类型</th>
                                                <th>标签</th>
                                                <th>日期</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr v-for="result in filteredRecognitionResults" :key="result.id"
                                                :class="{ active: selectedResult?.id === result.id }"
                                                @click="viewResult(result)">
                                                <td>
                                                    <img :src="result.imageUrl" alt="图片" class="table-image">
                                                </td>
                                                <td>{{ getHasForeignObjectStatusFromDesc(result.fullDescription) }}</td>
                                                <td>{{ getForeignObjectTypeFromDesc(result.fullDescription) }}</td>
                                                <td class="description-cell">{{ result.folderTag }}</td>
                                                <td>{{ formatDate(result.timestamp) }}</td>
                                                <td>
                                                    <div class="result-actions-table">
                                                        <button class="action-btn view-btn" @click.stop="viewResult(result)">
                                                            <i class="fas fa-eye"></i>
                                                        </button>
                                                        <button class="action-btn export-btn" @click.stop="exportResult(result)">
                                                            <i class="fas fa-download"></i>
                                                        </button>
                                                        <button class="action-btn delete-btn" @click.stop="deleteResult(result)">
                                                            <i class="fas fa-trash"></i>
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>

                                <!-- 结果详情 -->
                                <div v-if="selectedResult" class="result-detail">
                                    <div class="detail-header">
                                        <span class="result-date">{{ formatDate(selectedResult.timestamp) }}</span>
                                        <button class="close-detail" @click="selectedResult = null">
                                            <i class="fas fa-times"></i>
                                        </button>
                                    </div>
                                    <div class="detail-content">
                                        <div class="result-image-large">
                                            <img :src="selectedResult.imageUrl" :alt="selectedResult.title">
                                        </div>
                                        <div class="result-description-full">
                                            <h4>详细描述</h4>
                                            <p>{{ selectedResult.fullDescription }}</p>
                                        </div>
                                    </div>
                                    <div class="detail-actions">
                                        <button class="action-btn" @click="exportResult(selectedResult)">
                                            <i class="fas fa-download"></i> 导出结果
                                        </button>
                                        <button class="action-btn danger" @click="deleteResult(selectedResult)">
                                            <i class="fas fa-trash"></i> 删除结果
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="activeTab === 'reports'" class="main-page-card">
                    <div class="reports-page">
                        <!-- 数据报告页面内容 -->
                        <div class="page-header">
                            <h1><i class="fas fa-chart-bar"></i> 数据报告</h1>
                            <p>分析检测数据趋势，生成专业报告</p>
                        </div>

                        <div class="reports-container">
                            <!-- 报告类型选择 -->
                            <div class="report-type-selector">
                                <div class="type-tabs">
                                    <button class="type-tab"
                                            :class="{ active: reportType === 'analysis' }"
                                            @click="reportType = 'analysis'">
                                        <i class="fas fa-chart-line"></i>
                                        数据分析报告
                                    </button>
                                    <button class="type-tab"
                                            :class="{ active: reportType === 'comparison' }"
                                            @click="reportType = 'comparison'">
                                        <i class="fas fa-balance-scale"></i>
                                        同比环比分析
                                    </button>
                                </div>
                            </div>

                            <!-- 参数配置区域 -->
                            <div class="report-config">
                                <div class="config-section">
                                    <h3>报告参数配置</h3>

                                    <!-- 数据分析报告配置 -->
                                    <div v-if="reportType === 'analysis'" class="analysis-config">
                                        <div class="config-row">
                                            <div class="config-item">
                                                <label>开始日期</label>
                                                <input type="date" v-model="analysisConfig.startDate">
                                            </div>
                                            <div class="config-item">
                                                <label>结束日期</label>
                                                <input type="date" v-model="analysisConfig.endDate">
                                            </div>
                                            <div class="config-item">
                                                <label>分析粒度</label>
                                                <select v-model="analysisConfig.analysisType">
                                                    <option value="daily">按日</option>
                                                    <option value="weekly">按周</option>
                                                    <option value="monthly">按月</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- 对比分析报告配置 -->
                                    <div v-if="reportType === 'comparison'" class="comparison-config">
                                        <div class="config-row">
                                            <div class="config-item">
                                                <label>当前期间开始</label>
                                                <input type="date" v-model="comparisonConfig.currentStartDate">
                                            </div>
                                            <div class="config-item">
                                                <label>当前期间结束</label>
                                                <input type="date" v-model="comparisonConfig.currentEndDate">
                                            </div>
                                            <div class="config-item">
                                                <label>对比类型</label>
                                                <select v-model="comparisonConfig.comparisonType">
                                                    <option value="yoy">同比</option>
                                                    <option value="mom">环比</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="config-actions">
                                        <button class="generate-btn" @click="generateReport" :disabled="isGeneratingReport">
                                            <i class="fas fa-magic"></i>
                                            <span v-if="!isGeneratingReport">生成报告</span>
                                            <span v-else>生成中...</span>
                                        </button>
                                        <button class="export-btn" @click="exportReport" :disabled="!reportData">
                                            <i class="fas fa-download"></i>
                                            导出Excel
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- 报告展示区域 -->
                            <div v-if="reportData" class="report-display">
                                <!-- 数据分析报告展示 -->
                                <div v-if="reportType === 'analysis' && reportData" class="analysis-report">
                                    <div class="report-summary">
                                        <h3>检测数据概览</h3>
                                        <div class="summary-cards">
                                            <div class="summary-card">
                                                <div class="card-icon">
                                                    <i class="fas fa-search"></i>
                                                </div>
                                                <div class="card-content">
                                                    <div class="card-value">{{ reportData.summary?.total_detections || 0 }}</div>
                                                    <div class="card-label">总检测数量</div>
                                                </div>
                                            </div>
                                            <div class="summary-card">
                                                <div class="card-icon warning">
                                                    <i class="fas fa-exclamation-triangle"></i>
                                                </div>
                                                <div class="card-content">
                                                    <div class="card-value">{{ reportData.summary?.total_foreign_objects || 0 }}</div>
                                                    <div class="card-label">异物检测数量</div>
                                                </div>
                                            </div>
                                            <div class="summary-card">
                                                <div class="card-icon success">
                                                    <i class="fas fa-check-circle"></i>
                                                </div>
                                                <div class="card-content">
                                                    <div class="card-value">{{ reportData.summary?.total_normal_components || 0 }}</div>
                                                    <div class="card-label">正常部件数量</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="report-charts">
                                        <div class="chart-section">
                                            <h4>时间序列趋势</h4>
                                            <div class="time-series-chart">
                                                <div v-for="item in (reportData.time_series || [])" :key="item.time_period" class="time-point">
                                                    <div class="time-label">{{ item.time_period }}</div>
                                                    <div class="time-data">
                                                        <div class="data-item">
                                                            <span class="data-label">总检测:</span>
                                                            <span class="data-value">{{ item.total_detections || 0 }}</span>
                                                        </div>
                                                        <div class="data-item">
                                                            <span class="data-label">异物:</span>
                                                            <span class="data-value warning">{{ item.foreign_objects || 0 }}</span>
                                                        </div>
                                                        <div class="data-item">
                                                            <span class="data-label">正常:</span>
                                                            <span class="data-value success">{{ item.normal_components || 0 }}</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="chart-section">
                                            <h4>类型分布</h4>
                                            <div class="distribution-charts">
                                                <!-- 异物类型分布图表 -->
                                                <div class="distribution-chart">
                                                    <h5>异物类型分布</h5>
                                                    <div class="vertical-bars">
                                                        <div v-for="(count, type) in (reportData.object_type_distribution || {})"
                                                             :key="type" class="bar-wrapper">
                                                            <div class="bar-container">
                                                                <div class="bar-fill"
                                                                     :style="{ height: getBarHeight(count, reportData.object_type_distribution || {}) + '%' }">
                                                                    <span class="value-label">{{ count }}</span>
                                                                </div>
                                                            </div>
                                                            <div class="bar-label">{{ type }}</div>
                                                        </div>
                                                    </div>
                                                </div>

                                                <!-- 部件类型分布图表 -->
                                                <div class="distribution-chart">
                                                    <h5>部件类型分布</h5>
                                                    <div class="vertical-bars">
                                                        <div v-for="(count, type) in (reportData.component_type_distribution || {})"
                                                             :key="type" class="bar-wrapper">
                                                            <div class="bar-container">
                                                                <div class="bar-fill"
                                                                     :style="{ height: getBarHeight(count, reportData.component_type_distribution || {}) + '%' }">
                                                                    <span class="value-label">{{ count }}</span>
                                                                </div>
                                                            </div>
                                                            <div class="bar-label">{{ type }}</div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- 对比分析报告展示 -->
                                <div v-if="reportType === 'comparison' && reportData && reportData.periods" class="comparison-report">
                                    <div class="report-summary">
                                        <h3>对比分析结果</h3>
                                        <div class="comparison-periods">
                                            <div class="period-info">
                                                <span class="period-label">当前期间:</span>
                                                <span class="period-value">{{ reportData.periods?.current?.start_date || '未知' }} 至 {{ reportData.periods?.current?.end_date || '未知' }}</span>
                                            </div>
                                            <div class="period-info">
                                                <span class="period-label">对比期间:</span>
                                                <span class="period-value">{{ reportData.periods?.comparison?.start_date || '未知' }} 至 {{ reportData.periods?.comparison?.end_date || '未知' }}</span>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="comparison-charts">
                                        <div class="chart-section">
                                            <h4>主要指标对比</h4>
                                            <div class="comparison-metrics">
                                                <div v-for="(data, metric) in (reportData.changes || {})" :key="metric" class="metric-card">
                                                    <div class="metric-header">
                                                        <span class="metric-name">{{ getMetricName(metric) }}</span>
                                                        <span class="metric-change" :class="getChangeClass(data?.change_rate || 0)">
                                                            {{ formatChangeRate(data?.change_rate || 0) }}
                                                        </span>
                                                    </div>
                                                    <div class="metric-values">
                                                        <div class="current-value">
                                                            <span class="value-label">当前:</span>
                                                            <span class="value-number">{{ data?.current || 0 }}</span>
                                                        </div>
                                                        <div class="previous-value">
                                                            <span class="value-label">对比:</span>
                                                            <span class="value-number">{{ data?.previous || 0 }}</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="chart-section">
                                            <h4>详细类型对比</h4>
                                            <div class="detailed-comparison">
                                                <div class="comparison-table">
                                                    <div class="table-header">
                                                        <div class="header-cell">类型</div>
                                                        <div class="header-cell">当前期间</div>
                                                        <div class="header-cell">对比期间</div>
                                                        <div class="header-cell">变化率</div>
                                                    </div>
                                                    <div v-for="(data, type) in (reportData.object_type_changes || {})" :key="'obj-'+type" class="table-row">
                                                        <div class="table-cell">异物-{{ type }}</div>
                                                        <div class="table-cell">{{ data?.current || 0 }}</div>
                                                        <div class="table-cell">{{ data?.previous || 0 }}</div>
                                                        <div class="table-cell" :class="getChangeClass(data?.change_rate || 0)">
                                                            {{ formatChangeRate(data?.change_rate || 0) }}
                                                        </div>
                                                    </div>
                                                    <div v-for="(data, type) in (reportData.component_type_changes || {})" :key="'comp-'+type" class="table-row">
                                                        <div class="table-cell">部件-{{ type }}</div>
                                                        <div class="table-cell">{{ data?.current || 0 }}</div>
                                                        <div class="table-cell">{{ data?.previous || 0 }}</div>
                                                        <div class="table-cell" :class="getChangeClass(data?.change_rate || 0)">
                                                            {{ formatChangeRate(data?.change_rate || 0) }}
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 加载状态 -->
                            <div v-if="isGeneratingReport" class="loading-state">
                                <div class="loading-spinner"></div>
                                <p>正在生成报告，请稍候...</p>
                            </div>

                            <!-- 空状态 -->
                            <div v-if="!reportData && !isGeneratingReport" class="empty-state">
                                <i class="fas fa-chart-bar"></i>
                                <p>请配置报告参数并生成报告</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, computed, onMounted, nextTick, onBeforeUnmount } from 'vue';
    import { useRouter } from 'vue-router';
    import axios from 'axios';


    const MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB
    const isSending = ref(false);

    // 新增函数：将文件转换为Base64
    const fileToBase64 = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    };

    // 新增函数：验证图片文件
    const validateImageFile = (file) => {
        if (!file.type.match('image.*')) {
            alert('请选择图片文件 (JPG, PNG, GIF)');
            return false;
        }

        if (file.size > MAX_FILE_SIZE) {
            alert(`文件大小不能超过 ${MAX_FILE_SIZE / 1024 / 1024}MB`);
            return false;
        }

        return true;
    };

    // 连接状态管理 - 改为基于真实通信状态
    const connectionStatus = ref('connecting'); // 初始为连接中
    const connectionStatusText = computed(() => '已连接');
    const connectionStatusClass = computed(() => 'status-connected');
    // 新增：检查连接状态的函数
    const checkConnection = async () => {
        try {
            // 创建空的FormData（不带实际内容）
            const formData = new FormData();
            // 发送测试请求
            await sendToBackend(formData);
        } catch (error) {
            // 不处理错误，sendToBackend已经更新了状态
        }
    };

    //输入框
    const textArea = ref(null);

    // 导航状态
    const activeTab = ref('chat');

    // 聊天页面数据
    const chatHistory = ref(null);
    const messageInput = ref('');
    const isTyping = ref(false);
    // 多图上传相关
    const uploadedFiles = ref([]); // 支持多图
    const fileInput = ref(null);
    const showSwitch = ref(true); // 控制开关显示

    // 新增模式切换相关
    const isDetailedMode = ref(false); // 控制是否为详细模式，默认为简易模式
    const modeText = computed(() => isDetailedMode.value ? '详细模式' : '简易模式');
    const toggleMode = () => {
        isDetailedMode.value = !isDetailedMode.value;
        // 如果从详细模式切换回简易模式，需要清空selectedResult
        if (!isDetailedMode.value) {
            selectedResult.value = null;
        }
    };

    // 辅助函数：从 fullDescription 中提取"是否有异物"+顺便显示标签（在哪个分组下）
    const getHasForeignObjectStatusFromDesc = (fullDescription) => {
        if (!fullDescription || typeof fullDescription !== 'string') return '未知';
        const lines = fullDescription.split('\n');
        if (lines.length >= 2) {
            const statusLine = lines[1].trim();
            if (statusLine === '是') return '存在异物';
            if (statusLine === '否') return '无异物';
        }
        // 尝试从VLM返回的自然语言中查找关键词
        if (fullDescription.includes('存在异物')) return '存在异物';
        if (fullDescription.includes('无异物')) return '无异物';
        return '未知';
    };

    // 辅助函数：从 fullDescription 中提取类型信息
    const getForeignObjectTypeFromDesc = (fullDescription) => {
        if (!fullDescription || typeof fullDescription !== 'string') return '未知';

        // 定义关键词映射（统一为中文返回）
        const categoryMap = {
            // 异物类型
            foreign: {
                '风筝': '风筝',
                'kite': '风筝',
                '垃圾': '垃圾',
                'trash': '垃圾',
                '鸟巢': '鸟巢',
                'nest': '鸟巢',
                '气球': '气球',
                'balloon': '气球',
                '其他异物': '其他异物',
                'other': '其他异物'
            },
            // 部件类型
            component: {
                '均压环': '均压环',
                '复合绝缘子': '复合绝缘子',
                '挂点金具': '挂点金具',
                '玻璃绝缘子': '玻璃绝缘子',
                '连接金具': '连接金具',
                '防震锤': '防震锤',
                '其他部件': '其他部件',
                'other': '其他部件'
            }
        };
        // 检查描述开头
        const isForeign = fullDescription.startsWith('存在异物');
        const isNonForeign = fullDescription.startsWith('无异物');

        // 确定要使用的映射表
        const mapToUse = isNonForeign ? categoryMap.component : categoryMap.foreign;

        // 将描述转换为小写以进行不区分大小写的匹配
        const lowerDesc = fullDescription.toLowerCase();

        // 按关键词长度从长到短排序（避免部分匹配问题）
        const sortedKeywords = Object.keys(mapToUse).sort((a, b) => b.length - a.length);

        // 在描述中搜索关键词
        for (const keyword of sortedKeywords) {
            const lowerKeyword = keyword.toLowerCase();

            // 检查关键词是否出现在描述中
            if (lowerDesc.includes(lowerKeyword)) {
                return mapToUse[keyword];
            }
        }

        // 默认返回类型
        if (isNonForeign) {
            return '无'; // 无异物时也没找到部件类型
        }
        return isForeign ? '未知异物' : '未知'; // 存在异物但未匹配到具体类型
    };

    // 新增: 是否有异物状态
    const hasForeignObject = ref(null); // null 表示未选择，true 为"是"，false 为"否"
    const foreignObjectType = ref(''); // 新增：异物类型
    const otherForeignObjectType = ref(''); // 新增：其他异物类型输入

    // 新增: 部件类型状态
    const componentType = ref(''); // 部件类型
    const otherComponentType = ref(''); // 其他部件类型输入

    // 新增: 位置描述
    const locationDescription = ref('');

    // 增量学习页面数据
    const incrementalFileInput = ref(null);
    const incrementalImage = ref(null);
    const incrementalImagePreview = ref(null);
    const sceneDescription = ref('');
    const selectedCategory = ref('');
    const newCategory = ref('');
    const learningRate = ref(0.001);
    const epochs = ref(5);
    const batchSize = ref(16);
    const categories = ref(['动物', '植物', '交通工具', '家具', '电子产品', '食品']);

    // 新增历史会话相关状态
    const searchQuery = ref('');
    const dateFilter = ref('all');
    const historySessions = ref([]);
    const selectedSession = ref(null);
    const sessionToDelete = ref(null);
    const showDeleteConfirm = ref(false);
    const isDeleting = ref(false);
    const showDeleteSuccess = ref(false);
    const deleteError = ref(null);

    // 聊天消息历史
    const messages = ref([
        {
            sender: 'ai',
            content: '您好！我是电力检测 AI助手，有什么我可以帮您的吗？',
            timestamp: ''
        }
    ]);

    const conversationId = ref(null); // 当前对话id

    async function createConversationAPI(name) {
        const res = await fetch('http://127.0.0.1:8080/chat/conversations', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('access_token')
            },
            body: JSON.stringify({ name })
        });
        if (!res.ok) throw new Error('创建对话失败');
        return await res.json();
    }

    // 存储消息到后端
    async function storeMessageAPI({
        conversation_id,
        sender,
        content,
        content_type,
        oss_urls = [],
        base64_images = []
    }) {
        const res = await fetch('http://127.0.0.1:8080/chat/store_message', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('access_token')
            },
            body: JSON.stringify({
                conversation_id,
                sender,
                content,
                content_type,
                oss_urls,
                base64_images
            })
        });
        if (!res.ok) throw new Error('消息存储失败');
        return await res.json();
    }

    // 拉取某个会话的所有消息
    async function fetchConversationMessages(conversationId) {
        const res = await fetch(`http://127.0.0.1:8080/chat/conversations/${conversationId}/messages`, {
            method: 'GET',
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('access_token')
            }
        });
        if (!res.ok) throw new Error('获取消息失败');
        return await res.json();
    }
    async function selectConversation(conv) {
        conversationId.value = conv.id;
        try {
            const msgList = await fetchConversationMessages(conv.id);
            // 转换为前端展示格式
            messages.value = msgList.map(msg => ({
                sender: msg.sender,
                content: msg.content,
                timestamp: msg.created_at ? new Date(msg.created_at).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }) : '',
                images: (msg.oss_urls || []).map(url => url), // 如有图片
                content_type: msg.content_type
            }));
            // 滚动到底部
            nextTick(() => scrollToBottom());
        } catch (e) {
            messages.value = [];
            alert('加载消息失败');
        }
    }

    const adjustTextareaHeight = () => {
        nextTick(() => {
            if (textArea.value) {
                textArea.value.style.height = 'auto';
                textArea.value.style.height = `${Math.min(textArea.value.scrollHeight, 200)}px`;
                textArea.value.style.overflowY = textArea.value.scrollHeight > 200 ? 'auto' : 'hidden';
            }
        });
    };

    // 计算属性
    const isFormValid = computed(() => {
        // 检查图片是否已上传
        if (!incrementalImage.value) {
            return false;
        }

        // 检查是否有异物是否已选择
        if (hasForeignObject.value === null) {
            return false;
        }

        // 如果有异物，则检查异物类型
        if (hasForeignObject.value === true) {
            if (!foreignObjectType.value) {
                return false; // 异物类型未选择
            }
            if (foreignObjectType.value === 'other' && !otherForeignObjectType.value.trim()) {
                return false; // 其他异物类型为空
            }
        } else if (hasForeignObject.value === false) {
            // 如果没有异物，则检查部件类型
            if (!componentType.value) {
                return false; // 部件类型未选择
            }
            if (componentType.value === 'other' && !otherComponentType.value.trim()) {
                return false; // 其他部件类型为空
            }
        }

        // 检查位置描述是否填写
        if (!locationDescription.value.trim()) {
            return false; // 位置描述为空
        }

        return true; // 所有检查通过
    });

    const finalCategory = computed(() => {
        if (selectedCategory.value === 'new') {
            return newCategory.value;
        }
        return selectedCategory.value;
    });

    // 新增: 位置描述的动态标签和占位符
    const locationLabel = computed(() => {
        return hasForeignObject.value === false ? '描述图中部件位置' : '描述图中异物位置';
    });

    const locationPlaceholder = computed(() => {
        return hasForeignObject.value === false ? '请输入部件的详细位置描述...' : '请输入异物的详细位置描述...';
    });
    // 聊天页面方法
    const openFileSelector = () => {
        fileInput.value.click();
    };

    // 多图上传处理
    const handleImageUpload = async (event) => {
        const files = Array.from(event.target.files);
        for (const file of files) {
            if (file.type.startsWith('image/')) {
                if (validateImageFile(file)) {
                    uploadedFiles.value.push(file);
                }
            } else if (file.type.startsWith('video/')) {
                IsVedioMode.value = true;//上传视频模式
                // 上传视频到后端，提取关键帧
                const formData = new FormData();
                formData.append('video', file);
                try {
                    const res = await axios.post('http://127.0.0.1:8080/extract_keyframes', formData);
                    // 假设后端返回 { images: [base64, ...] }
                    if (res.data && Array.isArray(res.data.images)) {
                        res.data.images.forEach((base64, idx) => {
                            const imageFile = base64ToFile(base64, `frame_${idx + 1}.jpg`);
                            uploadedFiles.value.push(imageFile);
                        });
                        alert(`视频已自动提取${res.data.images.length}帧图片，注意：上传视频目前只支持快速模式！`);
                    } else {
                        alert('未能提取关键帧图片');
                        IsVedioMode.value = false; // 重置
                    }
                } catch (e) {
                    alert('视频处理失败，请重试');
                    console.error(e);
                    IsVedioMode.value = false; // 重置
                }
            } else {
                alert('仅支持图片或视频文件');
            }
        }
        fileInput.value.value = '';
    };

    const removeFile = (index) => {
        uploadedFiles.value.splice(index, 1);
        console.log('after remove:', uploadedFiles.value); // 打印当前的文件列表

        // 检查删除后是否还有图片
        if (uploadedFiles.value.length === 0) {
            IsVedioMode.value = false; // 没有图片了，将视频模式设为false,免得上传了视频又不发送
        }
    };

    const addNewLine = (event) => {
        event.preventDefault();
        messageInput.value += '\n';
        adjustTextareaHeight();
    };

    let IsVedioMode = ref(false); // 默认值为 false ,是否上传视频

    //发送消息函数
    const sendMessage = async () => {
        if (isSending.value) return;
        if (!messageInput.value.trim() && uploadedFiles.value.length === 0) return;
        if (!(uploadedFiles.value.length === 0) && (!imageTag.value.trim())) { // 新增验证条件:有图片时图片标签不能为空
            alert("图片标签不能为空！");
            return;
        }

        // 1. 如果是新对话，先创建对话
        if (!conversationId.value) {
            try {
                const conv = await createConversationAPI(messageInput.value);
                conversationId.value = conv.id;
            } catch (e) {
                console.error('创建对话失败:', e);
                return;
            }
        }

        // 处理图片转base64
        let base64Images = [];
        if (uploadedFiles.value.length > 0) {
            base64Images = await Promise.all(uploadedFiles.value.map(fileToBase64));
        }

        // 判断消息类型
        let contentType = 'text';
        if (base64Images.length > 0 && messageInput.value) {
            contentType = 'mixed';
        } else if (base64Images.length > 0) {
            contentType = 'image';
        }

        if (uploadedFiles.value.length > 1) {   //多图上传，在这里实现逻辑：把列表图片一张一张调用VLM，每张独立，发送到后端，接受结果不显示在聊天页面，但是打印在前端控制台，显示跳转到识别结果按钮，再清空输入什么的return
            // 添加用户消息
            const userMsg = {
                sender: 'user',
                content: messageInput.value,
                timestamp: getCurrentTime(),
                images: uploadedFiles.value.map(f => URL.createObjectURL(f))
            };
            messages.value.push(userMsg);

            // 存储消息到后端
            try {
                await storeMessageAPI({
                    conversation_id: conversationId.value,
                    sender: 'user',
                    content: userMsg.content,
                    content_type: contentType,
                    oss_urls: [],
                    base64_images: base64Images
                });
            } catch (e) {
                console.error('消息存储失败:', e);
            }

            // 显示发送状态
            isSending.value = true;
            scrollToBottom();

            const TempText = messageInput.value;
            const TempImageTag = imageTag.value; // 保存标签值
            // 清空输入和标签
            messageInput.value = '';
            imageTag.value = '';
            if (textArea.value) {
                textArea.value.style.height = '60px';
            }

            try {
                // 为每张图片创建独立的FormData并发送
                const allResults = []; // 收集所有处理结果

                for (const file of uploadedFiles.value) {
                    const formData = new FormData();
                    formData.append('image', file);

                    // 添加相同的文本消息（如果有）
                    if (TempText.trim()) {
                        if (IsVedioMode.value === false) {
                            if (showSwitch.value === true)//思考模式
                            { formData.append('text', "思考模式：" + TempText.trim()); }
                            else {
                                formData.append('text', "快速模式：" + TempText.trim());
                            }
                        }
                        else {       //上传了视频,锁定为“快速模式”，管你模式开关选的什么
                            formData.append('text', "快速模式：" + TempText.trim());
                        }
                    }

                    // 发送到后端
                    const response = await fetch('http://localhost:5000/api/message', {
                        method: 'POST',
                        body: formData
                    });

                    if (!response.ok) {
                        console.error(`图片 ${file.name} 处理失败: ${response.status}`);
                        continue;
                    }

                    const data = await response.json();

                    // 收集结果
                    allResults.push({
                        file: file,
                        data: data
                    });

                    //在这里连接到数据库，现在先打印到控制台
                    console.log(`图片 ${file.name} 识别结果:`, data);
                }

                // 所有图片处理完成后，统一存储到后端
                try {
                    const userId = await fetchCurrentUserId();
                    if (!userId) {
                        alert('用户未登录，无法保存检测结果');
                    } else if (uploadedFiles.value.length > 0) {
                        // 图片转base64
                        const base64List = await Promise.all(
                            uploadedFiles.value.map(file => fileToBase64(file))
                        );
                        // 构造items
                        const items = base64List.map((base64, index) => ({
                            image_base64: base64,
                            detection_info: allResults[index]?.data.vlm_response || "处理失败"
                        }));
                        // 构造请求体
                        const groupPayload = {
                            user_id: userId,
                            title: TempImageTag, // 使用保存的标签值
                            items
                        };
                        // 调用后端保存
                        await axios.post('http://127.0.0.1:8080/detection/group/', groupPayload);
                    }
                } catch (e) {
                    console.error('存储检测结果失败:', e);
                }

                // 添加跳转按钮
                messages.value.push({
                    sender: 'ai',
                    timestamp: getCurrentTime(),
                    isJumpButton: true
                });
                nextTick(() => {
                    scrollToBottom();
                });

                // 存储消息到后端
                try {
                    await storeMessageAPI({
                        conversation_id: conversationId.value,
                        sender: 'ai',
                        content: "跳转识别结果",
                        content_type: "text",
                        oss_urls: [],
                        base64_images: []
                    });
                } catch (e) {
                    console.error('消息存储失败:', e);
                }

            } catch (error) {
                console.error('多图处理失败:', error);
                messages.value.push({
                    sender: 'ai',
                    content: `图片处理失败: ${error.message}`,
                    timestamp: getCurrentTime()
                });
            } finally {
                isSending.value = false;
                uploadedFiles.value = [];
            }

            IsVedioMode.value = false;
            return; // 多图处理完毕，直接返回
        }

        try {
            isSending.value = true;
            scrollToBottom();


            // 添加用户消息
            const userMsg = {
                sender: 'user',
                content: messageInput.value,
                timestamp: getCurrentTime(),
                images: uploadedFiles.value.map(f => URL.createObjectURL(f))
            };
            // 存储消息到后端
            try {
                await storeMessageAPI({
                    conversation_id: conversationId.value,
                    sender: 'user',
                    content: userMsg.content,
                    content_type: contentType,
                    oss_urls: [],
                    base64_images: base64Images
                });
            } catch (e) {
                console.error('消息存储失败:', e);
            }

            messages.value.push(userMsg);
            const TempImageTag = imageTag.value; // 保存标签值

            // 清空输入和标签
            messageInput.value = '';
            imageTag.value = '';
            if (textArea.value) {
                textArea.value.style.height = '60px';
            }

            // 创建FormData对象
            const formData = new FormData();

            // 添加文本消息
            if (userMsg.content) {
                if (IsVedioMode.value === false) {      //没上传视频
                    if (showSwitch.value === true) { formData.append('text', "思考模式：" + userMsg.content); }
                    else {
                        formData.append('text', "快速模式：" + userMsg.content);
                    }
                }
                else {       //上传了视频,锁定为“快速模式”，管你模式开关选的什么
                    formData.append('text', "快速模式：" + userMsg.content);
                }
            }

            // 添加图片文件
            for (const file of uploadedFiles.value) {
                formData.append('image', file);

            }

            // 发送到后端
            const response = await fetch('http://localhost:5000/api/message', {
                method: 'POST',
                body: formData
            });

            if (!response.ok) {
                throw new Error(`后端请求失败: ${response.status}`);
            }

            const data = await response.json();

            // 将VLM回复添加到消息列表
            if (data.vlm_response) {
                messages.value.push({
                    sender: 'ai',
                    content: data.vlm_response,
                    timestamp: getCurrentTime()
                });
                nextTick(() => {
                    scrollToBottom(); // 确保新消息可见
                });
                // 存储消息到后端
                try {
                    await storeMessageAPI({
                        conversation_id: conversationId.value,
                        sender: 'ai',
                        content: data.vlm_response,
                        content_type: "text",
                        oss_urls: [],
                        base64_images: []
                    });
                } catch (e) {
                    console.error('消息存储失败:', e);
                }
            }

            IsVedioMode.value = false;

            try {
                const userId = await fetchCurrentUserId();
                if (!userId) {
                    alert('用户未登录，无法保存检测结果');
                } else if (uploadedFiles.value.length > 0) {
                    // 图片转base64
                    const base64List = await Promise.all(
                        uploadedFiles.value.map(file => fileToBase64(file))
                    );
                    // 构造items
                    const items = base64List.map(base64 => ({
                        image_base64: base64,
                        detection_info: data.vlm_response
                    }));
                    // 构造请求体
                    const groupPayload = {
                        user_id: userId,
                        title: TempImageTag, // 使用保存的标签值
                        items
                    };
                    // 调用后端保存
                    await axios.post('http://127.0.0.1:8080/detection/group/', groupPayload);
                }
            } catch (e) {
                console.error('存储检测结果失败:', e);
            }

        } catch (error) {
            console.error('发送消息失败:', error);
            // 添加错误消息
            messages.value.push({
                sender: 'ai',
                content: `请求失败: ${error.message}`,
                timestamp: getCurrentTime()
            });
            scrollToBottom();
        } finally {
            isSending.value = false;
            IsVedioMode.value = false;
            uploadedFiles.value = []; // 清空上传的文件
        }
    };

    // 改为基于实际通信
    const sendToBackend = async (formData) => {
        try {
            // 发送前更新状态为连接中
            connectionStatus.value = 'connecting';

            const response = await fetch('http://localhost:5000/api/message', {
                method: 'POST',
                body: formData
            });
            if (response.ok) {
                // 成功响应表示连接正常
                connectionStatus.value = 'connected';
                const data = await response.json();
                console.log('后端响应:', data);
                // 将VLM回复添加到消息列表
                if (data.vlm_response) {
                    messages.value.push({
                        sender: 'ai',
                        content: data.vlm_response,
                        timestamp: getCurrentTime()
                    });
                }
                return data;
            } else {
                // HTTP错误状态
                connectionStatus.value = 'error';
                throw new Error(`后端请求失败: ${response.status}`);
            }

        } catch (error) {
            // 网络错误或响应错误
            connectionStatus.value = error.message.includes('Failed to fetch')
                ? 'disconnected'
                : 'error';
            console.error('发送到后端失败:', error);
            throw error;
        }
    };

    // 修改函数：添加消息（保持原功能）
    const addMessage = (sender, content, timestamp, image = null) => {
        messages.value.push({ sender, content, timestamp, image });
    };

    const getCurrentTime = () => {
        const now = new Date();
        return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
    };

    const scrollToBottom = () => {
        if (chatHistory.value) {
            chatHistory.value.scrollTop = chatHistory.value.scrollHeight;
        }
    };

    // 增量学习页面方法
    const openIncrementalFileSelector = () => {
        incrementalFileInput.value.click();
    };

    const handleIncrementalImageUpload = (event) => {
        const file = event.target.files[0];
        if (!file) return;

        if (!file.type.match('image.*')) {
            alert('请选择图片文件 (JPG, PNG)');
            return;
        }

        incrementalImage.value = file;
        incrementalImagePreview.value = URL.createObjectURL(file);
    };

    const removeIncrementalImage = () => {
        incrementalImage.value = null;
        incrementalImagePreview.value = null;
        if (incrementalFileInput.value) {
            incrementalFileInput.value.value = '';
        }
    };

    //上传增量学习数据
    const submitIncrementalData = async () => {
        if (!isFormValid.value) {
            alert('请填写所有必填项并上传图片！');
            return;
        }

        // ============== 构建符合要求的字符串 ==============
        // 构建6行格式的字符串
        let textData = "";

        // 第一行：图中是否存在异物
        textData += "图中是否存在异物\n";

        // 第二行：是/否
        if (hasForeignObject.value === true) {
            textData += "是\n";
        } else {
            textData += "否\n";
        }

        // 第三行：选择问题类型
        if (hasForeignObject.value === true) {
            textData += "图中的异物是什么？\n";
        } else {
            textData += "图中的部件是什么？\n";
        }

        // 第四行：具体类型
        if (hasForeignObject.value === true) {
            const finalForeignObjectType = foreignObjectType.value === 'other' ? otherForeignObjectType.value : foreignObjectType.value;
            textData += finalForeignObjectType + "\n";
        } else {
            const finalComponentType = componentType.value === 'other' ? otherComponentType.value : componentType.value;
            textData += finalComponentType + "\n";
        }

        // 第五行：位置描述标题
        textData += "描述图中异物（部件）的位置\n";

        // 第六行：位置描述内容
        textData += locationDescription.value;
        // ============== 修改结束 ==============

        const formData = new FormData();
        formData.append('image', incrementalImage.value);
        formData.append('text', textData); // 添加构建的文本数据

        try {
            // ============== 发送到正确的后端端点 ==============
            const response = await axios.post('http://localhost:5000/api/learn', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            });

            if (response.status === 200) {
                alert('训练数据已成功提交！');
                resetForm();
            } else {
                alert('提交失败: ' + (response.data.detail || '未知错误'));
            }
        } catch (error) {
            console.error('提交增量学习数据失败:', error);
            alert('提交增量学习数据失败，请检查网络或服务器！');
        }
    };

    const resetForm = () => {
        incrementalImage.value = null;
        incrementalImagePreview.value = null;
        hasForeignObject.value = null;
        foreignObjectType.value = '';
        otherForeignObjectType.value = '';
        componentType.value = ''; // 重置部件类型
        otherComponentType.value = ''; // 重置其他部件类型
        locationDescription.value = ''; // 重置位置描述
        if (incrementalFileInput.value) {
            incrementalFileInput.value.value = '';
        }
    };

    // 跳转到历史会话并加载数据,点击“历史会话”时
    const jumpToHistory = () => {
        activeTab.value = 'history';
        loadHistory();
    };


    // 加载历史会话
    const loadHistory = async () => {
        try {
            // 1. 获取所有对话
            const convRes = await fetch('http://127.0.0.1:8080/chat/conversations', {
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + localStorage.getItem('access_token')
                }
            });
            if (!convRes.ok) throw new Error('获取历史会话失败');
            const conversations = await convRes.json();

            // 2. 并发获取每个对话的消息
            const sessionsWithMessages = await Promise.all(
                conversations.map(async conv => {
                    const msgRes = await fetch(`http://127.0.0.1:8080/chat/conversations/${conv.id}/messages`, {
                        method: 'GET',
                        headers: {
                            'Authorization': 'Bearer ' + localStorage.getItem('access_token')
                        }
                    });
                    let messages = [];
                    if (msgRes.ok) {
                        const msgList = await msgRes.json();
                        // 转换为前端展示格式
                        messages = msgList.map(msg => ({
                            sender: msg.sender,
                            content: msg.content,
                            timestamp: msg.created_at ? formatDate(msg.created_at) : '', // 使用formatDate
                            images: (msg.oss_urls || []), // 新增
                            base64_images: (msg.base64_images || []) // 可选
                        }));
                    }
                    //console.log('messages:', messages); // 这里打印
                    // 取最后一条消息内容
                    const lastMessage = messages.length > 0 ? messages[messages.length - 1].content : '';
                    // 组装结构
                    return {
                        id: String(conv.id),
                        title: conv.name,
                        lastMessage,
                        createdAt: new Date(conv.created_at),
                        messages
                    };
                })
            );

            // 3. 赋值给historySessions
            historySessions.value = sessionsWithMessages;
        } catch (e) {
            historySessions.value = [];
            alert('加载历史会话失败');
        }
    };

    //显示日期
    const formatDate = (dateString) => {
        // 处理空值情况
        if (!dateString) return '';

        try {
            // 创建Date对象
            const date = new Date(dateString);

            // 加8小时（转换为北京时间）
            date.setHours(date.getHours() + 8);

            // 格式化为 YYYY-MM-DD HH:mm 格式
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
        } catch (e) {
            console.error('日期格式化错误:', e);
            return '日期格式错误';
        }
    };

    // 选择会话
    const selectSession = (session) => {
        selectedSession.value = session;
    };

    // 恢复会话
    const restoreSession = (session) => {
        // 实际应用中这里应该将消息恢复到聊天界面
        conversationId.value = session.id;
        messages.value = [...session.messages];
        activeTab.value = 'chat';
        nextTick(() => {
            scrollToBottom();
        });
    };

    // 导出会话
    const exportSession = (session) => {
        const dataStr = JSON.stringify(session, null, 2);
        const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);

        const exportFileDefaultName = `会话_${session.id}.json`;

        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportFileDefaultName);
        linkElement.click();
    };

    // 确认删除
    const confirmDelete = (session) => {
        sessionToDelete.value = session;
        showDeleteConfirm.value = true;
    };

    // 删除会话
    const deleteSession = async () => {
        if (!sessionToDelete.value) return;

        isDeleting.value = true;
        deleteError.value = null;

        try {
            // 调用后端删除接口
            await deleteConversationAPI(sessionToDelete.value.id);

            //  前端同步删除
            historySessions.value = historySessions.value.filter(
                s => s.id !== sessionToDelete.value.id
            );

            if (selectedSession.value?.id === sessionToDelete.value.id) {
                selectedSession.value = null;
            }

            showDeleteSuccess.value = true;
            setTimeout(() => {
                showDeleteSuccess.value = false;
            }, 3000);
        } catch (error) {
            deleteError.value = '删除会话失败，请稍后重试';
            console.error('删除会话失败:', error);
        } finally {
            isDeleting.value = false;
            showDeleteConfirm.value = false;
            sessionToDelete.value = null;
        }
    };


    //过滤历史会话
    const filteredHistory = computed(() => {
        let filtered = historySessions.value;

        // 应用搜索过滤
        if (searchQuery.value) {
            const query = searchQuery.value.toLowerCase();
            filtered = filtered.filter(session =>
                (session.title && session.title.toLowerCase().includes(query)) ||
                (session.lastMessage && session.lastMessage.toLowerCase().includes(query))
            );
        }

        // 应用日期过滤
        const now = new Date();
        switch (dateFilter.value) {
            case 'today':
                filtered = filtered.filter(session => {
                    const d = new Date(session.createdAt);
                    return d.toDateString() === now.toDateString();
                });
                break;
            case 'week':
                const weekAgo = new Date();
                weekAgo.setDate(now.getDate() - 7);
                filtered = filtered.filter(session => new Date(session.createdAt) >= weekAgo);
                break;
            case 'month':
                const monthAgo = new Date();
                monthAgo.setMonth(now.getMonth() - 1);
                filtered = filtered.filter(session => new Date(session.createdAt) >= monthAgo);
                break;
            case 'year':
                const yearAgo = new Date();
                yearAgo.setFullYear(now.getFullYear() - 1);
                filtered = filtered.filter(session => new Date(session.createdAt) >= yearAgo);
                break;
        }

        // 按日期降序排序
        return filtered.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    });

    // 添加周期性连接检查
    let connectionCheckInterval = null;
    // 组件挂载后执行的操作
    onMounted(() => {
        checkConnection(); // 初始连接检查
        scrollToBottom();// 初始滚动到底部
        loadHistory();//加载历史会话

        adjustTextareaHeight();//调整输入框高度
        // 组件卸载时清除定时器
    });

    // 识别结果页面相关状态
    const recognitionResults = ref([]);
    const recognitionSearchQuery = ref('');
    const recognitionDateFilter = ref('all');
    const selectedResult = ref(null);
    const resultToDelete = ref(null);
    const showDeleteResultConfirm = ref(false);
    const isDeletingResult = ref(false);
    const showDeleteResultSuccess = ref(false);
    const deleteResultError = ref(null);
    const userId = ref(null);


    // 新增：文件夹搜索关键词
    const groupSearchQuery = ref('');
    // 新增：过滤后的文件夹列表
    const filteredGroupList = computed(() => {
        const arr = Array.isArray(groupList.value) ? groupList.value : [];
        if (!groupSearchQuery.value) return arr.filter(group => group && group.id && group.title);
        const query = groupSearchQuery.value.toLowerCase();
        return arr.filter(group =>
            group && group.id && group.title && group.title.toLowerCase().includes(query)
        );
    });

    //识别结果跳转过去自动刷新函数
    const jumpToRecognition = () => {
        activeTab.value = 'recognition';
        // 确保用户ID已获取
        fetchCurrentUserId().then(id => {
            if (id) {
                fetchGroups();
            }
        });
        scrollToBottom();
    };

    // 新增：图片标签文件夹相关变量  //没有用这个
    const selectedFolderTag = ref(null); // 默认选中"所有识别结果"

    const groupList = ref([]);
    const selectedGroupId = ref(null);


    // 识别结果筛选下拉框相关
    const foreignObjectStatusOptions = [
        { value: '', label: '全部' },
        { value: '存在异物', label: '存在异物' },
        { value: '无异物', label: '无异物' }
    ];
    const foreignObjectTypeOptions = [
        { value: '', label: '全部' },
        { value: '风筝', label: '风筝' },
        { value: '垃圾', label: '垃圾' },
        { value: '鸟巢', label: '鸟巢' },
        { value: '气球', label: '气球' },
        { value: '其他', label: '其他' }
    ];
    const componentTypeOptions = [
        { value: '', label: '全部' },
        { value: '均压环', label: '均压环' },
        { value: '复合绝缘子', label: '复合绝缘子' },
        { value: '挂点金具', label: '挂点金具' },
        { value: '玻璃绝缘子', label: '玻璃绝缘子' },
        { value: '连接金具', label: '连接金具' },
        { value: '防震锤', label: '防震锤' },
        { value: '其他', label: '其他' }
    ];
    const selectedForeignObjectStatus = ref('');
    const selectedType = ref('');





    onMounted(async () => {
        userId.value = await fetchCurrentUserId();
        console.log(userId.value);
        if (userId.value) {
            await fetchGroups(); // 只有获取到用户id后再拉取分组
        }
    });

    const fetchGroups = async () => {
        try {
            const res = await axios.get('http://127.0.0.1:8080/detection/groups/', { params: { user_id: userId.value } });
            console.log('fetchGroups 返回数据:', res.data);
            groupList.value = Array.isArray(res.data) ? res.data : [];
            console.log('groupList.value 赋值后:', groupList.value);
            if (groupList.value.length > 0) {
                // 默认加载第一个分组的识别结果，并传入其标题
                selectedGroupId.value = groupList.value[0].id;
                await fetchGroupItems(selectedGroupId.value, groupList.value[0].title);
            }
        } catch (e) {
            console.error('fetchGroups 出错:', e);
        }
    };

    //// 新增：当前分组标签状态
    //const currentGroupTag = ref('所有识别结果');

    // 获取分组下的检测项
    const fetchGroupItems = async (groupId, groupTitle) => {
        const res = await axios.get(`http://127.0.0.1:8080/detection/group/${groupId}`);
        console.log('接口返回', res.data);
        // 格式化为前端展示结构
        recognitionResults.value = Array.isArray(res.data.items)
            ? res.data.items.map(item => {
                let info = {};
                if (typeof item.detection_info === 'string' && item.detection_info.trim() !== '') {
                    try {
                        const parsed = JSON.parse(item.detection_info);
                        if (typeof parsed === 'object' && parsed !== null) {
                            info = parsed;
                        } else {
                            // 解析出来是字符串或数字
                            info = { text: parsed };
                        }
                    } catch (e) {
                        // 解析失败，直接用原始字符串
                        info = { text: item.detection_info };
                    }
                }
                return {
                    id: item.id,
                    title: info.title,
                    description: info.description || '',
                    imageUrl: item.oss_url,
                    status: info.status || 'normal',
                    confidence: info.confidence || 0,
                    timestamp: item.created_at,
                    detectedObject: info.detectedObject || '',
                    coordinates: info.coordinates || '',
                    fullDescription: info.text || '',
                    recommendations: info.recommendations || [],
                    folderTag: groupTitle, // 添加文件夹标签
                };
            })
            : [];
    };

    // 切换分组时加载对应检测项
    const onGroupChange = async (group) => { // 接收整个 group 对象
        selectedGroupId.value = group ? group.id : null;
        const groupTitle = group ? group.title : '所有识别结果';

        if (group === null) {
            await fetchAllGroupItems();
        } else {
            await fetchGroupItems(group.id, groupTitle);
        }
    };


    // 获取状态文本
    const getStatusText = (status) => {
        switch (status) {
            case 'normal': return '正常';
            case 'warning': return '警告';
            case 'danger': return '危险';
            case 'processing': return '处理中';
            default: return '未知';
        }
    };

    // 选择识别结果
    const selectResult = (result) => {
        selectedResult.value = result;
    };

    // 查看结果详情
    const viewResult = (result) => {
        selectedResult.value = result;
        console.log('查看结果详情:', result);
        // alert(`查看结果: ${result.title}`); // 移除此行，因为详情将在页面内显示
    };

    // 导出识别结果
    const exportResult = (result) => {
        const dataStr = JSON.stringify(result, null, 2);
        const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);
        const exportFileDefaultName = `识别结果_${result.id}.json`;

        const linkElement = document.createElement('a');
        linkElement.setAttribute('href', dataUri);
        linkElement.setAttribute('download', exportFileDefaultName);
        linkElement.click();
    };

    // 确认删除识别结果  ///根本没有弹窗呀
    const confirmDeleteResult = (result) => {
        resultToDelete.value = result;
        showDeleteResultConfirm.value = true;
    };

    const deleteResult = async (result) => {
        resultToDelete.value = result;
        //if (!resultToDelete.value) return;

        isDeletingResult.value = true;
        deleteResultError.value = null;
        console.log(1111);

        try {
            // 1. 调用后端删除接口
            await axios.delete(`http://127.0.0.1:8080/detection/item/${resultToDelete.value.id}`);

            // 2. 前端同步删除
            recognitionResults.value = recognitionResults.value.filter(
                r => r.id !== resultToDelete.value.id
            );

            if (selectedResult.value?.id === resultToDelete.value.id) {
                selectedResult.value = null;
            }

            showDeleteResultSuccess.value = true;
            setTimeout(() => {
                showDeleteResultSuccess.value = false;
            }, 3000);
        } catch (error) {
            deleteResultError.value = '删除识别结果失败，请稍后重试';
            console.error('删除识别结果失败:', error);
        } finally {
            isDeletingResult.value = false;
            showDeleteResultConfirm.value = false;
            resultToDelete.value = null;
        }
    };


    //识别结果筛选函数
    const filteredRecognitionResults = computed(() => {
        let filtered = recognitionResults.value;

        // 应用搜索过滤
        if (recognitionSearchQuery.value) {
            const query = recognitionSearchQuery.value.toLowerCase();
            filtered = filtered.filter(result =>
                (result.title && result.title.toLowerCase().includes(query)) ||
                (result.description && result.description.toLowerCase().includes(query)) ||
                (result.detectedObject && result.detectedObject.toLowerCase().includes(query))
            );
        }

        // 应用标签文件夹过滤
        if (selectedFolderTag.value !== null) {
            filtered = filtered.filter(result => result.tag === selectedFolderTag.value);
        }

        // 应用日期过滤
        const now = new Date();
        switch (recognitionDateFilter.value) {
            case 'today':
                filtered = filtered.filter(result => {
                    const d = new Date(result.timestamp);
                    return d.toDateString() === now.toDateString();
                });
                break;
            case 'week':
                const weekAgo = new Date();
                weekAgo.setDate(now.getDate() - 7);
                filtered = filtered.filter(result => new Date(result.timestamp) >= weekAgo);
                break;
            case 'month':
                const monthAgo = new Date();
                monthAgo.setMonth(now.getMonth() - 1);
                filtered = filtered.filter(result => new Date(result.timestamp) >= monthAgo);
                break;
            case 'year':
                const yearAgo = new Date();
                yearAgo.setFullYear(now.getFullYear() - 1);
                filtered = filtered.filter(result => new Date(result.timestamp) >= yearAgo);
                break;
        }

        // 中英文关键词映射表
        const keywordMap = {
            // 异物类型
            '风筝': ['风筝', 'kite'],
            '垃圾': ['垃圾', 'trash', 'garbage'],
            '鸟巢': ['鸟巢', 'nest', 'bird_nest'],
            '气球': ['气球', 'balloon'],
            '其他': ['其他', 'other'],

            // 部件类型
            '均压环': ['均压环', 'equalizing_ring'],
            '复合绝缘子': ['复合绝缘子', 'composite_insulator'],
            '挂点金具': ['挂点金具', 'hanging_point_hardware'],
            '玻璃绝缘子': ['玻璃绝缘子', 'glass_insulator'],
            '连接金具': ['连接金具', 'connecting_hardware'],
            '防震锤': ['防震锤', 'vibration_damper'],
            '其他部件': ['其他部件', 'other_component']
        };

        // 应用异物状态筛选
        if (selectedForeignObjectStatus.value) {
            filtered = filtered.filter(item => {
                return item.fullDescription &&
                    item.fullDescription.includes(selectedForeignObjectStatus.value);
            });
        }

        // 应用类型筛选（支持中英文）
        if (selectedType.value) {
            const keywords = keywordMap[selectedType.value] || [selectedType.value];
            filtered = filtered.filter(item => {
                return item.fullDescription &&
                    keywords.some(kw => item.fullDescription.includes(kw));
            });
        }

        // 按时间降序排序
        return filtered.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
    });

    // 图片标签输入
    const imageTag = ref('');


    // 识别结果描述
    const getRecognitionDescription = (result) => {
        // 如果fullDescription有内容，优先展示
        if (result.fullDescription && typeof result.fullDescription === 'string') {
            return result.fullDescription;
        }
        // 兼容旧数据结构
        if (result.isForeignObjectDetected && result.foreignObjectDescription) {
            return result.foreignObjectDescription;
        }
        return '无异物描述';
    };


    // 识别结果标题
    const getRecognitionTitle = (result) => {
        // 确保 fullDescription 存在且是字符串
        if (result.fullDescription && typeof result.fullDescription === 'string') {
            // 检查是否包含"存在异物"
            if (result.fullDescription.includes('存在异物')) {
                return '存在异物';
            }
            // 检查是否包含"无异物"
            else if (result.fullDescription.includes('无异物')) {
                return '无异物';
            }
        }

        // 默认情况：无法确定状态
        return '未知状态';
    };


    const router = useRouter();

    const handleLogout = () => {
        localStorage.removeItem('access_token');
        // localStorage.removeItem('user_info'); // 如果有的话
        router.push('/login');
    };

    async function fetchCurrentUserId() {
        // 假设 access_token 已经保存在 localStorage
        const token = localStorage.getItem('access_token');
        if (!token) {
            // 未登录
            return null;
        }
        try {
            const res = await axios.get('http://127.0.0.1:8080/auth/me', {
                headers: {
                    Authorization: `Bearer ${token}`
                }
            });
            // 返回用户id
            return res.data.id;
        } catch (e) {
            // token 失效或未登录
            return null;
        }
    }
    function extractForeignObjectType(infoStr) {
        // 你可以根据实际业务调整关键词和返回内容
        if (!infoStr) return '';
        if (infoStr.includes('风筝')) return '风筝';
        if (infoStr.includes('垃圾')) return '垃圾';
        if (infoStr.includes('鸟巢')) return '鸟巢';
        if (infoStr.includes('气球')) return '气球';
        if (infoStr.includes('异物')) return '其他异物';
        return '';
    }

    const exportAllGroupsToExcel = async () => {
        try {
            const res = await axios.get('http://127.0.0.1:8080/detection/groups/', { params: { user_id: userId.value } });
            const groups = Array.isArray(res.data) ? res.data : [];
            let excelData = [];

            for (const group of groups) {
                const groupRes = await axios.get(`http://127.0.0.1:8080/detection/group/${group.id}`);
                if (Array.isArray(groupRes.data.items)) {
                    for (const item of groupRes.data.items) {
                        let infoStr = '';
                        if (typeof item.detection_info === 'string') {
                            try {
                                // 先尝试解析为JSON，如果是字符串则直接用
                                const parsed = JSON.parse(item.detection_info);
                                infoStr = typeof parsed === 'string' ? parsed : JSON.stringify(parsed, null, 2);
                            } catch {
                                infoStr = item.detection_info;
                            }
                        }
                        // 自动识别异物类型
                        const foreignObject = extractForeignObjectType(infoStr);

                        excelData.push({
                            分组名称: group.title,
                            图片链接: item.oss_url,
                            检测信息: infoStr,
                            异物类型: foreignObject
                        });
                    }
                }
            }

            // 排序逻辑
            const foreignObjectOrder = {
                '风筝': 1,
                '垃圾': 2,
                '鸟巢': 3,
                '气球': 4,
                '其他异物': 5,
                '': 99 // 没有异物类型的排最后
            };
            excelData.sort((a, b) => {
                const orderA = foreignObjectOrder[a.异物类型] !== undefined ? foreignObjectOrder[a.异物类型] : 98;
                const orderB = foreignObjectOrder[b.异物类型] !== undefined ? foreignObjectOrder[b.异物类型] : 98;
                return orderA - orderB;
            });

            // 生成Excel
            const ws = XLSX.utils.json_to_sheet(excelData);
            ws['!cols'] = [
                { wch: 20 }, // 第一列宽20字符
                { wch: 40 }, // 第二列宽40字符
                { wch: 60 }, // 第三列宽60字符
                { wch: 20 }  // 第四列宽20字符（根据你的实际列数调整）
            ];
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, '检测结果');
            XLSX.writeFile(wb, '检测结果导出.xlsx');
        } catch (e) {
            alert('导出失败！');
            console.error('exportAllGroupsToExcel 出错:', e);
        }
    };


    const validGroupList = computed(() => {
        const arr = Array.isArray(groupList.value) ? groupList.value : [];
        console.log('validGroupList 计算:', arr);
        return arr.filter(group => group && group.id && group.title);
    });

    // 1. 新增API调用
    async function deleteConversationAPI(conversationId) {
        const res = await fetch(`http://127.0.0.1:8080/chat/conversations/${conversationId}`, {
            method: 'DELETE',
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('access_token')
            }
        });
        if (!res.ok) throw new Error('删除会话失败');
        return await res.json();
    }

    const fetchAllGroupItems = async () => {
        try {
            // 1. 获取所有分组
            const res = await axios.get('http://127.0.0.1:8080/detection/groups/', { params: { user_id: userId.value } });
            const groups = Array.isArray(res.data) ? res.data : [];
            let allItems = [];
            // 2. 遍历每个分组，获取检测项
            for (const group of groups) {
                const groupRes = await axios.get(`http://127.0.0.1:8080/detection/group/${group.id}`);
                if (Array.isArray(groupRes.data.items)) {
                    allItems = allItems.concat(groupRes.data.items.map(item => {
                        let info = {};
                        if (typeof item.detection_info === 'string' && item.detection_info.trim() !== '') {
                            try {
                                const parsed = JSON.parse(item.detection_info);
                                if (typeof parsed === 'object' && parsed !== null) {
                                    info = parsed;
                                } else {
                                    info = { text: parsed };
                                }
                            } catch (e) {
                                info = { text: item.detection_info };
                            }
                        }
                        return {
                            id: item.id,
                            title: info.title,
                            description: info.description || '',
                            imageUrl: item.oss_url,
                            status: info.status || 'normal',
                            confidence: info.confidence || 0,
                            timestamp: item.created_at,
                            detectedObject: info.detectedObject || '',
                            coordinates: info.coordinates || '',
                            fullDescription: info.text || '',
                            recommendations: info.recommendations || [],
                            // 新增：添加分组名称作为标签
                            folderTag: group.title // 使用分组名称
                        };
                    }));
                }
            }
            recognitionResults.value = allItems;
        } catch (e) {
            console.error('fetchAllGroupItems 出错:', e);
            recognitionResults.value = [];
        }
    };

    function base64ToFile(base64, filename) {
        const arr = base64.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
    }

    // 下载所有分组Excel
    const downloadAllGroupsExcel = async () => {
        try {
            const res = await axios.get(`http://127.0.0.1:8080/detection/export_excel/`, {
                params: { user_id: userId.value },
                responseType: 'blob'
            });
            const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `export_user_${userId.value}.xlsx`);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        } catch (e) {
            alert('Excel导出失败！');
            console.error('downloadAllGroupsExcel 出错:', e);
        }
    };


    // 数据报告相关状态
    const reportType = ref('analysis'); // analysis, comparison
    const reportData = ref(null);
    const isGeneratingReport = ref(false);

    // 分析报告配置
    const analysisConfig = ref({
        startDate: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 30天前
        endDate: new Date().toISOString().split('T')[0], // 今天
        analysisType: 'daily'
    });

    // 对比报告配置
    const comparisonConfig = ref({
        currentStartDate: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 7天前
        currentEndDate: new Date().toISOString().split('T')[0], // 今天
        comparisonType: 'yoy'
    });

    // 数据报告相关方法
    // 添加计算柱状图高度的方法
    const getBarHeight = (count, distribution) => {
        if (!distribution || Object.keys(distribution).length === 0) return 0;
        const maxValue = Math.max(...Object.values(distribution));
        return maxValue > 0 ? (count / maxValue) * 100 : 0;
    };
    const generateReport = async () => {
        if (isGeneratingReport.value) return;

        isGeneratingReport.value = true;
        reportData.value = null;

        try {
            const userId = await fetchCurrentUserId();
            if (!userId) {
                alert('用户未登录，无法生成报告');
                return;
            }

            let response;
            if (reportType.value === 'analysis') {
                // 生成数据分析报告
                const params = new URLSearchParams({
                    user_id: userId.toString(),
                    start_date: analysisConfig.value.startDate,
                    end_date: analysisConfig.value.endDate,
                    analysis_type: analysisConfig.value.analysisType
                });

                response = await axios.get(`http://127.0.0.1:8080/detection/reports/analysis/?${params}`);
            } else {
                // 生成对比分析报告
                const params = new URLSearchParams({
                    user_id: userId.toString(),
                    current_start_date: comparisonConfig.value.currentStartDate,
                    current_end_date: comparisonConfig.value.currentEndDate,
                    comparison_type: comparisonConfig.value.comparisonType
                });

                response = await axios.get(`http://127.0.0.1:8080/detection/reports/comparison/?${params}`);
            }

            // 验证响应数据
            if (response.data) {
                reportData.value = response.data;
            } else {
                throw new Error('服务器返回空数据');
            }

        } catch (error) {
            console.error('生成报告失败:', error);
            let errorMessage = '生成报告失败，请检查网络连接或稍后重试';

            if (error.response) {
                // 服务器返回错误状态码
                if (error.response.status === 404) {
                    errorMessage = '未找到相关数据，请检查时间范围设置';
                } else if (error.response.status === 400) {
                    errorMessage = '请求参数错误，请检查日期格式';
                } else if (error.response.status === 500) {
                    errorMessage = '服务器内部错误，请稍后重试';
                }
            } else if (error.request) {
                // 网络错误
                errorMessage = '网络连接失败，请检查网络设置';
            }

            alert(errorMessage);
            reportData.value = null;
        } finally {
            isGeneratingReport.value = false;
        }
    };

    const exportReport = async () => {
        if (!reportData.value) return;

        try {
            const userId = await fetchCurrentUserId();
            if (!userId) {
                alert('用户未登录，无法导出报告');
                return;
            }

            const params = new URLSearchParams({
                user_id: userId.toString(),
                start_date: reportType.value === 'analysis' ? analysisConfig.value.startDate : comparisonConfig.value.currentStartDate,
                end_date: reportType.value === 'analysis' ? analysisConfig.value.endDate : comparisonConfig.value.currentEndDate,
                report_type: reportType.value
            });

            const response = await axios.get(`http://127.0.0.1:8080/detection/reports/export/?${params}`, {
                responseType: 'blob'
            });

            // 下载文件
            const blob = new Blob([response.data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            });
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `detection_report_${userId}_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.xlsx`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);

        } catch (error) {
            console.error('导出报告失败:', error);
            alert('导出报告失败，请稍后重试');
        }
    };

    // 辅助方法
    const getBarWidth = (value, distribution) => {
        if (!distribution || Object.keys(distribution).length === 0) return 0;
        const maxValue = Math.max(...Object.values(distribution));
        return maxValue > 0 ? (value / maxValue) * 100 : 0;
    };

    const getMetricName = (metric) => {
        const names = {
            'total_detections': '总检测数量',
            'foreign_objects': '异物检测数量',
            'normal_components': '正常部件数量'
        };
        return names[metric] || metric;
    };

    const formatChangeRate = (changeRate) => {
        // 如果是字符串类型（如"新增"），直接返回
        if (typeof changeRate === 'string') {
            return changeRate;
        }
        // 如果是数字类型，按原来的逻辑处理
        if (typeof changeRate === 'number') {
            if (changeRate > 0) return `+${changeRate}%`;
            if (changeRate < 0) return `${changeRate}%`;
            return '0%';
        }
        return '0%';
    };

    const getChangeClass = (changeRate) => {
        // 如果是字符串类型（如"新增"），返回positive类
        if (typeof changeRate === 'string') {
            if (changeRate === '新增') return 'positive';
            if (changeRate === '0%') return 'neutral';
            return 'neutral';
        }
        // 如果是数字类型，按原来的逻辑处理
        if (typeof changeRate === 'number') {
            if (changeRate > 0) return 'positive';
            if (changeRate < 0) return 'negative';
            return 'neutral';
        }
        return 'neutral';
    };

</script>

<style scoped>
    @import'./assets/style/HomeView.css';
    @import'./assets/style/HomeViewDetailMode.css';
</style>